package cn.kawa.product.service.impl;


import cn.kawa.basic.exception.BusinessException;
import cn.kawa.basic.service.IBaiduAiAuditService;
import cn.kawa.product.domain.ProductDetail;
import cn.kawa.product.mapper.ProductDetailMapper;
import cn.kawa.product.mapper.ProductMapper;
import cn.kawa.product.domain.Product;

import cn.kawa.product.service.IProductService;
import cn.kawa.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductDetailMapper productDetailMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;


    @Override
    public void delete(Long id) {
        ProductDetail productDetail= productDetailMapper.loadByProdId(id);
        if(productDetail!=null){
            productDetailMapper.remove(productDetail.getId());
        }
        super.delete(id);
    }

    @Override
    public void add(Product product) {

        Boolean aBoolean = baiduAiAuditService.textAudit(product.getName());
        if(aBoolean){
            // 先添加product，返回自增的主键
            productMapper.save(product);
            // 再添加product_datail
            ProductDetail productDetail = product.getProductDetail();
            //[重要]：此处保存了自增的id
            productDetail.setProductId(product.getId());
            productDetailMapper.save(productDetail);
        }else{
            throw  new BusinessException("图片或名称不合法~");
        }

    }

    @Override
    public void update(Product product) {
        // product
        productMapper.update(product);
        //从页面传的product对象获取productDetail-Net对象
        ProductDetail productDetailNet = product.getProductDetail();
        //通过product.id 获取 productDetail对象
        ProductDetail productDetail = productDetailMapper.loadByProdId(product.getId());
        //把数据库对应productDetail
        productDetailNet.setId(productDetail.getId());
        // detail
        productDetailMapper.update(product.getProductDetail());
    }
    

    /**
     *
     * @param ids
     */
    @Override
    public void onSale(List<Long> ids) {
        //1.审核通过上架，没通过自定异常，，每次审核都要保存log


        /**
         * 改状态：state=1
         * 改上架时间:new Date()
         *
         */
        productMapper.onSale(ids,new Date());

    }

    @Override
    public void offSale(List<Long> ids) {
        /**
         * 改状态：state=0
         * 改下架时间:new Date()
         *
         */
        productMapper.offSale(ids,new Date());
    }
}
